<?php namespace sacvoyage\storage;

use \sacvoyage\storage\View;

class Table extends View {

	/*
	 * unerlying table must exist
	 */
	public function __construct($gateway, $name) {
		View::__construct($gateway, $name);
	}

	/*
	 * sql-expression to retreive content; 
	 * can be simple table name or somplex sql-expression
	 */
	public function getName() {
		return $this->getExpression();
	}

	public function create($schema) {
		$this->query("CREATE TABLE `{$this->getName()}` ($schema)");
	}

	public function createTemporary($schema) {
		$this->query("CREATE TEMPORARY TABLE `{$this->getName()}` ($schema)");
	}

	public function drop() {
		$this->query("DROP TABLE `{$this->getName()}`");
	}

	public function delete($sqlWhere=null) {
		$this->query(
			"DELETE FROM `{$this->getName()}`".
			$sqlWhere ? " WHERE ".$sqlWhere : ""
		);
	}

	public function insert($columns, $rows) {
		if(!is_enumerative_array($rows)) {
			$values=array($rows);
		}

		$sqlValues=array();
		foreach($rows as $row) {
			$values=array();
			foreach($columns as $column) {
				if(!array_key_exists($column, $row) || is_null($value)) {
					$values[]='NULL';
				} else {
					$value=$row[$column];
					if(is_string($value)) {
						$values[]="'".$this->escape($value)."'";
					} elseif(is_numeric($value)) {
						$values[]=(string)$value;
					} elseif(is_boolean($value)) {
						$values[]=$value ? '1' : '0';
					} else {
						throw new Exception('error value');
					}
				}
			}
			$sqlValues[]='('.implode(', ', $values).')';
		}


		$sql="INSER INTO `{$this->getName()}` (".
		     implode(', ', $columns).') VALUES '.
		     implode(', ', $sqlValues);


	}


}

?>
